const AK = process.env.WEN_XIN_AK;
const SK = process.env.WEN_XIN_SK;

export async function getAccessToken() {
    const options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
    }
    const res = await fetch(options.url, options);
    const {access_token} = await res.json();
    return access_token;
}

class BotService {
    private getPrompt({content = ''} = {}) {
        return [
            // '请帮我用大纲目录总结一下下面这段话',
            '请帮我用极其简单的语句总结一下下面这段话讲述了什么',
            '要求: 字数不超过100字',
            `内容: ${content}`
        ].join('\n');
    }

    async summaryContentWithStream(content: string, callback = (data: ReadableStream<Uint8Array>) => {}) {
        const params = {
            'method': 'POST',
            'url': 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token='
                + '24.19e33603bc2b58eb6e71f66033e5c0a7.2592000.1712895048.282335-56304817',
            'headers': {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "messages": [
                    {
                        "role": "user",
                        "content": this.getPrompt({content})
                    }
                ],
                "disable_search": false,
                "enable_citation": false,
                "stream": true
            })
        };
        const res = await fetch(params.url, params)
        return res.body!;
    }

    async summaryContent(content: string) {
        const options = {
            'method': 'POST',
            'url': 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=' + await getAccessToken(),
            'headers': {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "messages": [
                    {
                            "role": "user",
                            "content": this.getPrompt({content})
                    }
                ],
                "disable_search": false,
                "enable_citation": false
            })
        };
        const res = await fetch(options.url, options);
        return res.json();
    }
}

const botService = new BotService();
export default botService;
